package edu.xmut.proxy.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 代理工厂，用来创建代理对象
 */
public class ProxyFactory {
    private TrainStation trainStation = new TrainStation();

    /**
     * 获取代理对象，通过JDK提供的Proxy.newProxyInstance方法获取
     *
     * @return
     */
    public SellTickets getProxyObject() {
        return (SellTickets) Proxy.newProxyInstance(
                trainStation.getClass().getClassLoader(),
                trainStation.getClass().getInterfaces(),
                new SellTicketInvocationHandler(trainStation)
        );
    }
}

class SellTicketInvocationHandler implements InvocationHandler {

    private final TrainStation trainStation;

    public SellTicketInvocationHandler(TrainStation trainStation) {
        this.trainStation = trainStation;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
        // 1.增强代理对象
        System.out.println("代售点收取额外费用(jdk动态代理)");
        // 2.调用目标对象的方法
        Object result = method.invoke(trainStation, args);
        return result;
    }
}
